import { toQuery, getTopLevelDomain } from './utils';

export default class BeylaCls {
  constructor() {
    this.nation = '';
    this.portal = window._portal;
    this.startTime = new Date().getTime();
    this.baseUrl = getTopLevelDomain();
  }

  // 1. 以后自己上报用
  _customReport(payload) {
    // 安全检查
    if (!payload || typeof payload !== 'object') {
      console.warn('[数据上报] 尝试上报一个无效的数据:', payload);
      return;
    }

    // 当前：只在控制台打印日志
    console.log(
      '[数据上报]',
      `事件: ${payload.eventName || '未知事件'}`,
      payload
    );

    /*
    如果需要把、报点击游戏和离开界面时的数据传到自己接口的代码
    // fetch(...)
    */

    //如果需要上报点击游戏和离开界面时上报tt和ga 的代码
    let ga_tt_event_name = '';
    const extras = JSON.parse(payload.extras || '{}');

    switch (payload.eventName) {
      case 'click_ve':
        ga_tt_event_name = 'select_content';
        break;
      case 'out_page':
        ga_tt_event_name = 'page_leave';
        break;
          case 'in_page':
        ga_tt_event_name = 'ViewContent'; 
        break;
      default:
        return; 
    }

    const ga_params = {
      content_type: 'game',
      content_id: extras.game_name || payload.pveCur,
      value: extras.time,
    };

    const tt_params = {
      content_id: extras.game_name,
      description: "User selected a game",
      value: extras.time, 
      currency: 'USD',
    };
    
    if (ga_tt_event_name === 'select_content') {
        tt_params.content_type = 'product'; 
    }
    
    // 上报给 GA, TT, 和 FB
    try {
      console.log(`[GA 上报] 事件: ${ga_tt_event_name}`, ga_params);
      window.gtag?.('event', ga_tt_event_name, ga_params);

      //tt上报放开

      console.log(`[TT 上报] 事件: ${ga_tt_event_name}`, tt_params);
      window.ttq?.track(ga_tt_event_name, tt_params);

      //fb上报
    //   if (window.fbq) {
    //   let fb_event_name = '';
    //   switch(ga_tt_event_name) {
    //     case 'select_content':
    //       fb_event_name = 'ViewContent'; 
    //       break;
    //     default:
    //       // 【新增】对于其他所有TT事件 (比如 'page_leave')，直接使用相同的事件名
    //       fb_event_name = ga_tt_event_name;
    //       break;
    //   }

    //   if (fb_event_name) {
    //       const fb_params = {
    //           content_ids: [ga_params.content_id], // FB 推荐用数组
    //           content_name: ga_params.content_id,
    //           content_type: 'product' // FB 也使用 'product'
    //       };
          
    //       // 如果是 page_leave 事件，可以把停留时间也报给 FB
    //       if (fb_event_name === 'page_leave') {
    //         fb_params.value = ga_params.value;
    //         fb_params.currency = 'USD';
    //       }

    //       console.log(`[FB 上报] 事件: ${fb_event_name}`, fb_params);
    //       window.fbq('track', fb_event_name, fb_params);
    //   }
    // }

    } catch (e) {
      console.error('上报时出错:', e);
    }
  }

  _logInit() {
    this._unloadPage();
    this._pageInitLog();
  }

  _unloadPage() {
    window.addEventListener('beforeunload', () => {
      this._pageOutLog();
    });
  }

  _pageInitLog() {
    const pveCur = `/${this.portal}/GameMain`;
    this._customReport({
      pveCur: pveCur,
      eventName: 'in_page',
      extras: JSON.stringify({
        nation: this.nation,
      }),
    });
  }

  _pageOutLog() {
    try {
      const endTime = new Date().getTime();
      const stayTime = endTime - this.startTime;
      this._customReport({
        pveCur: `/${this.portal}/GameMain`,
        eventName: 'out_page',
        extras: JSON.stringify({
          nation: this.nation,
          time: stayTime,
        }),
      });
    } catch (e) {
      console.warn('e2>', e);
    }
  }

  logShowVe(game) {
    if (!this) return '{}';
    const { name, url } = game || {};
    const pveCur = `/${this.portal}/GameMain/Main/game`;
    
    const { l_slot, b_slot } = window.curPortalConfig || {};
    const query = toQuery({ portal: this.portal, l_slot, b_slot });
    return JSON.stringify({
      isOutside: true,
      params: {
        pveCur: pveCur,
        eventName: 'show_ve',
        extras: JSON.stringify({
          nation: this.nation,
          game_name: name,
          game_url: `${this.baseUrl}${url}?${query}`,
        }),
      },
    });
  }

  gameClickReport(game) {
    if (!this) return;
    const { name, url } = game;
    const game_url = `${this.baseUrl}${url}?portal=${this.portal}`;
    this._customReport({
      pveCur: game_url,
      eventName: 'click_ve',
      extras: JSON.stringify({
        game_name: name,
        game_url,
      }),
    });
  }
}